package com.study.juc;

import java.util.concurrent.TimeUnit;

public class ThreadInterrupt {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println(" t1 被中断了 ");
                    break;
                }
                System.out.println(" t1 working ");
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            while (true){
                if (Thread.interrupted()){
                    System.out.println(" t2 被中断了 ");
                    break;
                }
                /**
                 * 下面这段代码会导致InterruptedException 后无限循环
                 * java.lang.InterruptedException: sleep interrupted
                 * 	at java.lang.Thread.sleep(Native Method)
                 * 	at com.study.juc.ThreadInterrupt.lambda$main$1(ThreadInterrupt.java:27)
                 * 	at java.lang.Thread.run(Thread.java:748)
                 */
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
                System.out.println(" t2 working ");
            }
        });
        t2.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread t3 = new Thread(() -> {
            t1.interrupt();
            t2.interrupt();
        });
        t3.start();
        Thread.currentThread().interrupt();
        System.out.println("Thread.interrupted() = " + Thread.interrupted());

        System.out.println("Thread.interrupted() = " + Thread.interrupted());


    }
}
